function ElectricCharge(graphics) {
  this.type = "electric_charge";
}

ElectricCharge.prototype = {
  edit : function() {
    this.show($("#item .content"));
    this.showOptions();
  },

  showOptions : function() {
    Graphics.prototype.showOptions.apply(this, arguments);
  },

  show : function(target) {
    if (target == null) { target = $("#item .content"); }
    target.html("<table class='electric_charge' style='width:100%; height:100%'>" +
      "<tr class='graphics'></tr><tr class='labels'></tr></table>");
    this.showGraphics(target);
    this.showLabels(target);
  },

  showGraphics : function(target) {
    var graphics = target.find(".graphics");
    var h = i2a("H-1");

    for (var i = 0; i < 3; i++) {
      graphics.append("<td style='width:33%'>" +
        "<canvas class='graphic-" + i + " border-1' width='280px' height='120px'></canvas></td>");
      var g = graphics.find(".graphic-" + i);
      g.ctx = g[0].getContext("2d");
      var p1, p2;
      switch (i) {
        case 0 : p1 = "+"; p2 = "+"; break;
        case 1 : p1 = "-"; p2 = "-"; break;
        case 2 : p1 = "+"; p2 = "-"; break;
      }
      var left = 100;
      var right  = 180;
      var y = 0.5 * g.height();
      var spacing = 24;
      if (p1 == p2) {
        for (var j = 0; j < 4; j++) {
          drawChargedParticle(g.ctx, left - j * spacing, y, 100, p1, 0.25 + j * 0.25);
          drawChargedParticle(g.ctx, right + j * spacing, y, 100, p2, 0.25 + j * 0.25);
        }
      } else {
        for (var k = 0; k < 4; k++) {
          drawChargedParticle(g.ctx, left + (k - 3) * spacing, y, 100, p1, 0.25 + k * 0.25);
          drawChargedParticle(g.ctx, right - (k - 3) * spacing, y, 100, p2, 0.25 + k * 0.25);
        }
      }
    }
  },

  showLabels : function(target) {
    var labels = target.find(".labels");
    labels.append("<td>Two positively charged particles will repel each other.</td>" +
      "<td>Two negatively charged particles will also repel each other.</td>" +
      "<td>Oppositely charged particles will attract each other.</td>");
  }
};

function drawChargedParticle(ctx, x, y, scale, charge, opacity) {
  var gradient = ctx.createRadialGradient(x - 0.04 * scale, y - 0.04 * scale, 0.04 * scale, x, y, 0.32 * scale);
  gradient.addColorStop(0, charge == "-" ?
    "rgba(255, 174, 206, " + opacity + ")" : "rgba(158, 206, 255, " + opacity + ")");
  gradient.addColorStop(1, "rgba(64, 64, 64, " + opacity + ")");
  ctx.fillStyle = gradient;
  ctx.fillCircle(x, y, 0.14 * scale);
  ctx.fillStyle = "rgba(96, 96, 96, " + opacity + ")";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.font = "bold " + Math.round(0.48 * scale) + "px sans-serif";
  switch (charge) {
    case "-" :
      ctx.font = Math.round(0.64 * scale) + "px sans-serif";
      ctx.fillText("-", x, y - 0.03 * scale);
      break;
    default :
      ctx.font = "bold " + Math.round(0.32 * scale) + "px sans-serif";
      ctx.fillText(charge, x, y - 0.02 * scale);
  }
}